<template>
  <view>
    <u-navbar :background="navbarBackground" :height="navigationHeight" :border-bottom="false" :title="orderStatusText"
      :immersive="true" title-color="#fff" back-icon-color="#fff"></u-navbar>
    <view class="page-address-wrap">
      <view :style="{ height: `${navBarHeight}px` }"></view>
      <view class="address-card">
        <view class="address-card-header am-flex-row-center">
          <image src="/static/images/icon-address.png" mode="aspectFill" class="address-card-adress-icon"></image>
          收货信息
        </view>
        <view class="address-user">
          <text class="username">{{ orderDetails.consigneeName }}</text>
          <text>{{ orderDetails.consigneePhone }}</text>
        </view>
        <text class="am-text-break address-info-text am-text-break">{{
          allAddress
        }}</text>
      </view>
    </view>
    <view class="order-card__products">
      <view class="order-card__goods" v-for="list in orderDetails.orderDetailVOList" :key="list.productVO.id"
        @click="goToDetails(list.productVO.id, list.productVO.buyProductStatus)">
        <view class="order-card__goods-cover">
          <image :src="$imageCutting(list.productVO.banner.split(',')[0], 120, 120)" mode="aspectFill"
            class="order-card__goods-img am-block am-wh-100"></image>
          <view class="am-flex-rc-center goods-bot-tag" v-if="[3, 4].includes(list.status)">{{ reGoodsTag(list.status)
            }}</view>
        </view>
        <view class="order-card__goods-con">
          <view class="order-card__goods-info">
            <view>
              <text class="order-card__goods-name am-line-clamp-two am-text-break">{{ list.productVO.name }}</text>
              <text class="specStyle">{{ list.productVO.spec }}</text>
            </view>
            <view class="order-card__goods-org">
              <view class="order-card__goods-price am-text-eill">{{ list.orderPrice }}元</view>
              <view class="order-card__goods-num">x{{ list.num }}</view>
            </view>
          </view>
          <view>
            <view v-if="orderDetails.originalPrice">
              <text class="original-price">原价: ¥{{ orderDetails.originalPrice }}</text>
            </view>
            <view v-if="list.orderPrice">
              <text class="order-details-total-text order-card-status--not-shipped">会员价: ¥{{
              list.orderPrice }}</text>
            </view>
          </view>
        </view>

      </view>

    </view>

    <view class="am-flex-rc-between order-card__goods-total">
      <text></text>
      <text class="order-card__total-text">
        共{{ orderDetails.orderDetailVOList.length }}件 合计：
        <text class="order-details-total-text order-card-status--not-shipped">¥{{ orderDetails.price || 0
          }}</text>（含运费:{{ freightShow(orderDetails.freight) }}）
      </text>
    </view>
    <view class="order-info-section">
      <view class="oder-info-item">
        <view class="order-info-label">订单状态</view>
        <view class="order-info-val">{{ orderStatusText }}</view>
      </view>
      <view class="oder-info-item">
        <view class="order-info-label">下单时间</view>
        <view class="order-info-val">{{
          $timestampToTime(orderDetails.createtime)
        }}</view>
      </view>
      <view class="oder-info-item">
        <view class="order-info-label">订单编号</view>
        <view class="order-info-val">{{ orderDetails.oid }}</view>
        <view class="am-flex-rc-center btn" @click="copy(orderDetails.oid)">复制</view>
      </view>
      <view class="oder-info-item" v-if="orderDetails.payTypeName">
        <view class="order-info-label">支付方式</view>
        <view class="order-info-val">{{ orderDetails.payTypeName }}</view>
      </view>
      <view class="oder-info-item" v-if="orderDetails.excomName">
        <view class="order-info-label">快递公司</view>
        <view class="order-info-val">{{ orderDetails.excomName }}</view>
      </view>
      <view class="oder-info-item" v-if="orderDetails.exnumber">
        <view class="order-info-label">快递单号</view>
        <view class="order-info-val">{{ orderDetails.exnumber }}</view>
        <view class="am-flex-rc-center btn" @click="copy(orderDetails.exnumber)">复制</view>
      </view>
      <view class="oder-info-item" v-if="orderDetails.remark">
        <view class="order-info-label">备注</view>
        <view class="order-info-val">{{ orderDetails.remark }}</view>
      </view>
      <template v-if="showAfterData">
        <view v-if="orderDetails.afterSalesOrders.applyRemark" class="oder-info-item">
          <view class="order-info-label">退款原因</view>
          <view class="order-info-val">
            <text class="am-text-break">{{
              orderDetails.afterSalesOrders.applyRemark
            }}</text>
          </view>
        </view>
        <view v-if="orderDetails.afterSalesOrders.refuseApplyRemark" class="oder-info-item">
          <view class="order-info-label">拒绝退款</view>
          <view class="order-info-val">
            <text class="am-text-break">{{
              orderDetails.afterSalesOrders.refuseApplyRemark
            }}</text>
          </view>
        </view>
        <view class="oder-info-item">
          <view class="order-info-label">申请时间</view>
          <view class="order-info-val">{{
            $timestampToTime(orderDetails.afterSalesTime)
          }}</view>
        </view>
      </template>
      <template v-if="orderDetails.status == 5 && orderDetails.closingReason">
        <view class="oder-info-item">
          <view class="order-info-label">取消原因</view>
          <view class="order-info-val">
            <text class="am-text-break">{{ orderDetails.closingReason }}</text>
          </view>
        </view>
        <view class="oder-info-item">
          <view class="order-info-label">申请时间</view>
          <view class="order-info-val">{{
            $timestampToTime(orderDetails.afterSalesTime)
          }}</view>
        </view>
      </template>
    </view>
    <!-- <pay-panel ref="payPanelRef" @paySuccess="paySuccessCb" @payFail="payFailCb" scene="order"></pay-panel> -->
    <payment-method ref="paymentRef" @payFail="payFailCb" @paySuccess="paySuccessCb" :scene="payScene"></payment-method>
    <template v-if="allowFtShow">
      <view class="page-footer-bar-place"></view>
      <view class="page-footer-bar am-flex-rc-between">
        <view></view>
        <view class="page-btn-wrap am-flex-row-center">
          <button class="u-reset-button page-btn-list page-btn--info" hover-class="page-btn-list--hover"
            @click="applyRefund" v-if="orderDetails.status === 0">
            申请退款
          </button>
          <button class="u-reset-button page-btn-list page-btn--info" hover-class="page-btn-list--hover"
            v-if="[0, -1].includes(orderDetails.status)" @click="editOrder">
            修改地址
          </button>
          <button class="u-reset-button page-btn-list page-btn--info" hover-class="page-btn-list--hover"
            @click="cancelRefund" v-if="orderDetails.status === 3">
            撤销申请
          </button>
          <button class="u-reset-button page-btn-list page-btn--info" hover-class="page-btn-list--hover"
            v-if="[-1].includes(orderDetails.status)" @click="cancelOrder">
            取消订单
          </button>
          <button class="u-reset-button page-btn-list page-btn--success" hover-class="page-btn-list--hover" v-if="isPay"
            @click="orderPay">
            付款
          </button>
          <button class="u-reset-button page-btn-list page-btn--success" hover-class="page-btn-list--hover"
            v-if="orderDetails.status === 1 || orderDetails.status === 2" @click="lookTransport">
            查看物流
          </button>
          <button class="u-reset-button page-btn-list page-btn--success-qs" hover-class="page-btn-list--hover"
            v-if="orderDetails.status === 1" @click="orderSign">
            确认签收
          </button>
          <button class="u-reset-button page-btn-list page-btn--info" hover-class="page-btn-list--hover"
            v-if="showAfterBtn" @click="orderAfterSales">
            申请售后
          </button>
        </view>
      </view>
    </template>
    <ordercancel :showCanle="showCanle" @close="onclose" @submit="submit"></ordercancel>
  </view>
</template>

<script>
import {
  apiApplyRefund,
  apiCancelOrder,
  apiCancelRefund,
  apiOrderDetails,
  apiOrderSign
} from '@/api/order.js'
import {
  UPDATE_ORDER_DETAILS,
  UPDATE_ORDER_LIST
} from '@/types/globalEventName'
import { navBarHeight, navigationHeight } from '@/utils/systemInfo.js'
import throttle from 'lodash-es/throttle'
import ordercancel from './components/order-cancel.vue'
// 允许售后的时间; 单位ms
const allCancelTime = 7 * 24 * 60 * 60 * 1000

// 最多允许申请售后的次数
const maxAllowAfterNum = 2
export default {
  data() {
    return {
      navigationHeight,
      navBarHeight,
      pageQuery: {},
      orderDetails: {
        orderDetailVOList: []
      },
      navbarBackground: {
        background: '#FE6507'
      },
      now: Date.now(),
      showCanle: false,
      type: 1
    }
  },
  components: {
    ordercancel
  },
  computed: {
    isPay() {
      return (
        this.orderDetails.status === -1 &&
        this.orderDetails.hasPartProductNotDelivery === 0 &&
        (this.orderDetails.parseAddressStatus === 0 ||
          this.orderDetails.parseAddressStatus === 2)
      )
    },
    freightShow() {
      return function (v) {
        return '￥' + (v ? v.toFixed(2) : '0.00')
      }
    },
    orderStatusText() {
      if (!this.orderDetails.oid) return ''
      let obj = {
        '-1': '待支付',
        0: '未发货',
        1: '待收货',
        2: '已签收',
        3: '售后中',
        4: '已退款',
        5: '交易关闭'
      }
      return obj[this.orderDetails.status] || ''
    },
    // footerBarShow() {
    // 	// 什么订单状态下需要footer bar 显示
    // 	let foterShowStatus = [0, -1];
    // 	return this.orderDetails.oid && foterShowStatus.includes(this.orderDetails.status);
    // },
    allowFtShow() {
      let orderDetails = this.orderDetails
      return (
        (orderDetails.oid && [0, -1, 1, 3].includes(orderDetails.status)) ||
        this.showAfterBtn
      )
    },
    showAfterBtn() {
      let orderDetails = this.orderDetails
      return (
        orderDetails.status === 2 &&
        this.now < orderDetails.canApplyTime + allCancelTime &&
        orderDetails.afterSalesNum < maxAllowAfterNum
      )
    },
    allAddress() {
      if (!this.orderDetails.oid) return ''
      let orderDetails = this.orderDetails
      return `${orderDetails.consigneeProvince}${orderDetails.consigneeCity}${orderDetails.consigneeCounty}${orderDetails.consigneeAddress}`
    },
    showAfterData() {
      // 售后中或者已退款显示
      // 已签收，并且申请过售后显示
      return (
        [3, 4].includes(this.orderDetails.status) ||
        (this.orderDetails.status === 2 && this.orderDetails.afterSalesNum > 0)
      )
    }
  },
  /**
   * @param {Object} options - 页面参数
   * @param {String} options.id - 订单id
   * */
  onLoad(options) {
    this.pageQuery = options
    if (options.id) {
      this.getDetails()
    }
    uni.$on(UPDATE_ORDER_DETAILS, this.updateOrder)
  },
  onUnload() {
    uni.$off(UPDATE_ORDER_DETAILS, this.updateOrder)
  },
  onPageScroll(e) {
    this.pageScrollHandle(e)
  },
  methods: {
    onclose() {
      this.showCanle = false
    },
    submit(val) {
      this.showCanle = false
      if (this.type == 1) {
        apiCancelOrder({ oid: this.orderDetails.oid, reason: val })
          .then((res) => {
            let { state, msg } = res.data
            if (state === 'OK') {
              this.getDetails()
              uni.$emit(UPDATE_ORDER_LIST)
              this.$am_toast.success(msg)
            } else {
              this.$am_toast.warning(msg)
            }
          })
          .catch(() => {
            this.$am_toast.error('操作失败，请重新尝试！')
          })
      } else {
        apiApplyRefund({ oid: this.orderDetails.oid, reason: val })
          .then((res) => {
            let { state, msg } = res.data
            if (state === 'OK') {
              this.getDetails()
              uni.$emit(UPDATE_ORDER_LIST)
              this.$am_toast.success(msg)
            } else {
              this.$am_toast.warning(msg)
            }
          })
          .catch(() => {
            this.$am_toast.error('操作失败，请重新尝试！')
          })
      }
    },
    copy(res) {
      uni.setClipboardData({
        data: res,
        success: () => {
          uni.showToast({
            title: '复制成功'
          })
        }
      })
    },
    pageScrollHandle: throttle(
      function (e) {
        if (e.scrollTop === 0) {
          this.navbarBackground = {
            background: '#FE6507'
          }
        } else {
          this.navbarBackground = {
            background: '#FE6507'
          }
        }
      },
      500,
      { leading: false, trailing: true }
    ),
    getDetails() {
      uni.showLoading({
        mask: true
      })
      apiOrderDetails({ id: this.pageQuery.id })
        .then((res) => {
          let { state, data, msg } = res.data
          if (state === 'OK') {
            this.orderDetails = data
            uni.hideLoading()
          } else {
            uni.hideLoading()
            this.$am_toast.warning(msg)
          }
        })
        .catch((err) => {
          uni.hideLoading()
          this.$am_toast.error('查询失败，请重新尝试！')
        })
    },
    // 查看物流
    lookTransport(id) {
      this.$u.route({
        url: '/pages/order/transport-detail',
        params: {
          id: this.orderDetails.oid
        }
      })
    },
    // 编辑订单
    editOrder() {
      this.$u.route('/pages/order/order-edit', { id: this.pageQuery.id })
    },
    // 点击付款
    orderPay(item) {
      // console.log(item)
      this.$refs.paymentRef.pay_out([this.orderDetails.oid])
    },
    // 支付成功
    paySuccessCb() {
      this.getDetails()
      uni.$emit(UPDATE_ORDER_LIST)
      uni.navigateTo({
        url: '/pages/place-order/pay-result'
      })
    },
    cancelOrder() {
      this.type = 1
      this.showCanle = true
    },
    updateOrder(data) {
      if (data.id === this.pageQuery.id) {
        this.getDetails()
      }
    },
    // 跳转商品详情
    goToDetails(id, status) {
      if (status == 0) {
        uni.navigateTo({
          url: `/pages/goods-details/goods-details?id=${id}`
        })
      } else {
        uni.navigateTo({
          url: `/pages/order/goods-delete`
        })
      }
    },
    // 支付失败
    payFailCb(p_data) {
      if (p_data.type === 'not_enough_stop') {
        this.$am_toast.warning(p_data.msg)
      }
    },
    reGoodsTag(status) {
      let obj = {
        3: '退款中',
        4: '已退款'
      }
      return obj[status] || ''
    },
    // 申请退款
    applyRefund() {
      this.type = 2
      this.showCanle = true
    },
    // 确认签收
    orderSign() {
      let item = this.orderDetails
      uni.showModal({
        title: '签收商品',
        content: '确定您已收到当前商品吗?',
        confirmColor: '#4BB019',
        success: (cancelRes) => {
          if (cancelRes.confirm) {
            uni.showLoading({
              mask: true
            })
            apiOrderSign({ oid: item.oid })
              .then((res) => {
                let { state, msg } = res.data
                uni.hideLoading()
                if (state === 'OK') {
                  this.getDetails()
                  uni.$emit(UPDATE_ORDER_LIST)
                } else {
                  this.$am_toast.warning(msg)
                }
              })
              .catch(() => {
                uni.hideLoading()
                this.$am_toast.error('操作失败，请重新尝试！')
              })
          }
        }
      })
    },
    // 撤销售后申请
    cancelRefund() {
      let item = this.orderDetails
      uni.showModal({
        title: '撤销申请',
        content: '确定撤销当前商品的售后申请？',
        confirmColor: '#4BB019',
        success: (cancelRes) => {
          if (cancelRes.confirm) {
            uni.showLoading({
              mask: true
            })
            apiCancelRefund({ oid: item.oid })
              .then((res) => {
                let { state, msg } = res.data
                uni.hideLoading()
                if (state === 'OK') {
                  this.$am_toast.success('撤销成功')
                  this.getDetails()
                  uni.$emit(UPDATE_ORDER_LIST)
                } else {
                  this.$am_toast.warning(msg)
                }
              })
              .catch(() => {
                uni.hideLoading()
                this.$am_toast.error('操作失败，请重新尝试！')
              })
          }
        }
      })
    },
    // 申请售后
    orderAfterSales() {
      let item = this.orderDetails
      // if(item.payType == 'weChat'){
      // 	this.$am_toast.warning('微信支付订单暂不支持申请售后')
      // 	return
      // }else{
      this.$u.route({
        url: '/pages/order-after-sales/order-after-sales',
        params: {
          id: this.orderDetails.id
        }
      })
      // }
    }
  }
}
</script>

<style lang="scss" scoped>
$section-plr: 31rpx;

.order-card__products {
  padding: 30rpx $section-plr 0;
  margin-top: 20rpx;
  background-color: #fff;
}

.order-card__goods {
  display: flex;

  &+.order-card__goods {
    margin-top: 30rpx;
  }
}

.order-card__goods-cover {
  position: relative;
  overflow: hidden;
  width: 120rpx;
  height: 120rpx;
  flex-shrink: 0;
  border-radius: 8rpx;
}

.order-card__goods-img {}

.order-card__goods-con {
  flex: 1;
  width: 0;
  margin-left: 22rpx;
}

.order-card__goods-info {
  display: flex;
  justify-content: space-between;
}

.order-card__goods-name {
  flex-shrink: 0;
  width: 395rpx;
  font-size: 30rpx;
  line-height: 42rpx;
}

.order-card__goods-org {
  flex: 1;
  width: 0;
  margin-left: 15rpx;
  text-align: right;
}

.order-card__goods-price {
  line-height: 42rpx;
}

.order-card__goods-num {
  margin-top: 18rpx;
  font-size: 24rpx;
  color: #666;
}

.order-card__goods-total {
  padding: 0 $section-plr 20rpx;
  font-size: 30rpx;
  background-color: #fff;
}

.order-card__total-text {
  font-size: 24rpx;
  color: #ec5d29;
  line-height: 34rpx;
}

.order-details-total-text {
  color: #f65301;
}

.order-info-section {
  margin-top: 16rpx;
  padding: 10rpx 0;
  background: #fff;
}

.oder-info-item {
  display: flex;
  padding: 20rpx $section-plr;
  font-size: 26rpx;
  color: #666;
}

.order-info-label {
  width: 192rpx;
  flex-shrink: 0;
}

.order-info-val {
  flex: 1;
  width: 0;
}

.btn {
  color: #1790ff;
}

.page-address-wrap {
  padding-bottom: 16rpx;
  background: linear-gradient(360deg, #f79128 0%, #fe6507 100%);
}

.address-card {
  width: 718rpx;
  min-height: 198rpx;
  margin: 0 auto;
  padding: 30rpx 30rpx;
  background: #ffffff;
  box-shadow: 0px 2px 6px 0px #914317;
  border-radius: 20rpx;
}

.address-card-header {
  font-size: 36rpx;
  font-weight: 500;
  color: #000000;
}

.address-card-adress-icon {
  display: block;
  width: 36rpx;
  height: 36rpx;
  margin-right: 12rpx;
}

.address-user {
  margin-top: 30rpx;
  font-size: 26rpx;
  color: #333;

  .username {
    padding-right: 42rpx;
  }
}

.address-info-text {
  display: block;
  margin-top: 20rpx;
  font-size: 26rpx;
  color: #333;
}

.page-footer-bar {
  position: fixed;
  z-index: 1000;
  left: 0;
  bottom: 0;
  width: 750rpx;
  height: 98rpx;
  padding: 0 32rpx;
  background-color: #fff;
}

.page-footer-bar-place {
  height: 98rpx;
}

.page-btn-wrap {}

.page-btn-list {
  min-width: 146rpx;
  height: 66rpx;
  padding: 0 37rpx;
  line-height: 66rpx;
  text-align: center;
  font-size: 30rpx;
  font-weight: 500;
  border-radius: 32rpx;
  border-width: 1px;
  border-style: solid;

  &+.page-btn-list {
    margin-left: 49rpx;
  }
}

.page-btn--success {
  border-color: #fe6507;
  color: #fe6507;
}

.page-btn--success-qs {
  background: linear-gradient(132deg, #fe6507 0%, #f69027 100%);
  border-radius: 40px;
  color: #ffffff;
}

.page-btn--info {
  border-color: #999;
  color: #666;
}

.page-btn-list--hover {
  opacity: 0.7;
}

.goods-bot-tag {
  position: absolute;
  left: 0;
  bottom: 0;
  z-index: 10;
  width: 100%;
  height: 38rpx;
  font-size: 26rpx;
  color: #fff;
  background: rgba(0, 0, 0, 0.4);
}

.specStyle {
  margin-top: 10rpx;
  padding: 5rpx 10rpx;
  background: rgba(239, 239, 244, 0.5);
  color: #999999;
  border-radius: 4rpx;
  font-size: 22rpx;
}
</style>
